package com.kgc.publicprovider.service.impl;

import com.alibaba.fastjson.JSON;
import com.kgc.publiccommon.pojo.User;
import com.kgc.publiccommon.pojo.UserRole;
import com.kgc.publiccommon.util.CreateCode;
//import com.kgc.publiccommon.util.JwtUtil;
import com.kgc.publiccommon.util.ResponseMsg;
import com.kgc.publicprovider.mapper.UserMapper;
import com.kgc.publicprovider.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private JwtUtil jwtUtil;

    @Override
    public ResponseMsg login(String name, String password, String checkCode) {
        logger.info("UserServiceImpl login name:{},password:{},checkCode:{}", name, password, checkCode);

        // 校验验证码
        String storedCode = redisTemplate.opsForValue().get("code");
        if (storedCode == null || !storedCode.equalsIgnoreCase(checkCode)) {
            ResponseMsg msg = new ResponseMsg();
            msg.setCode("303");
            msg.setMsg("验证码错误");
            return msg;
        }

        ResponseMsg msg = new ResponseMsg();
        User user = userMapper.login(name);
        if (user == null) {
            msg.setCode("301");
            msg.setMsg("您还未注册");
            return msg;
        }
        if (!user.getPassword().equals(password)) {
            msg.setCode("302");
            msg.setMsg("用户名或密码错误");
            return msg;
        }

        // 生成 Token
        List<String> authorities = Arrays.asList("ROLE_USER"); // 示例权限，可根据实际角色动态获取
//        String token = jwtUtil.generateToken(user.getName(), authorities);

        // 将用户信息和 Token 放入返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
//        data.put("token", token);
        msg.setData(data);
        msg.setCode("200");
        msg.setMsg("登录成功");

        // 将用户信息存入 Redis
        redisTemplate.opsForValue().set(user.getName(), JSON.toJSONString(user));

        return msg;
    }

    @Override
    public String getCaptcha() {
        try {
            // 生成验证码
            String code = CreateCode.generateCode(4);
            redisTemplate.opsForValue().set("code", code, 60, TimeUnit.SECONDS);

            // 创建图片
            int width = 120, height = 40;
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = image.createGraphics();

            // 设置背景色
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);

            // 绘制干扰线
            Random random = new Random();
            for (int i = 0; i < 20; i++) {
                g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
                g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
            }

            // 绘制验证码文字
            g.setFont(new Font("Arial", Font.BOLD, 24));
            for (int i = 0; i < code.length(); i++) {
                g.setColor(new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
                g.drawString(String.valueOf(code.charAt(i)), 25 * i + 10, 28);
            }

            // 将图片转换为 Base64 编码
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            return base64Image;
        } catch (Exception e) {
            logger.error("getCaptcha is error", e);
            return null;
        }
    }

    @Override
    public ResponseMsg logout(String sessionId) {
        logger.info("UserServiceImpl logout is start...");
        ResponseMsg msg = new ResponseMsg();
        if (!redisTemplate.hasKey(sessionId)) {
            msg.setCode("404");
            msg.setMsg("会话不存在");
            return msg;
        }
        redisTemplate.delete(sessionId);
        msg.setCode("200");
        return msg;
    }

    @Override
    public ResponseMsg selectRoleById(int id) {
        logger.info("UserServiceImpl selectRoleById id:{}", id);
        ResponseMsg msg = new ResponseMsg();
        List<UserRole> userRoleList = userMapper.selectRoleById(id);
        if (userRoleList == null || userRoleList.isEmpty()) {
            msg.setCode("301");
            msg.setMsg("未查询到相关信息");
            return msg;
        }
        msg.setCode("200");
        msg.setData(userRoleList);
        return msg;
    }

    @Override
    public ResponseMsg selectAllUser() {
        return null;
    }

    @Override
    public ResponseMsg selectUserByMap(Map<String, Object> map) {
        return null;
    }
}



